<?php
/**
 * Created by Command.
 * User: Vito
 */

declare (strict_types = 1);

namespace app\logic;

use app\model\RoomLeaseRecord;
use app\exception\MessageException;
use app\model\Room;
use app\service\Wechat\WechatH5Service;
use app\logic\UserOauthLogic;
use app\model\PayRecord;
use app\model\User;
use think\facade\Db;
use app\model\ReturnRecord;
class RoomLeaseRecordLogic extends BaseLogic
{

    /**
     * 设置模型
     * @return string
     */
    protected function getModelName(): string
    {
        return RoomLeaseRecord::class;
    }
    /**
     * @Description: 驳回申请
     * @author: xiayu <cb1071403016@126.com>
     * @param [type] $params
     * @Date: 2023-06-25 14:57:16
     * @version: 1.0.0
     * @return [type]
     */    
    public function backRecord($params){
        $UserOauth  = new UserOauthLogic;
        $wechat     = new WechatH5Service;
        $admin = $this->user->getUserInfo();
        // halt($admin['nickname']);
        $record = RoomLeaseRecord::find($params['id']);
        if(!$record ){
            halt('record');
            throw new MessageException('驳回失败，找不到该记录');
        }
        $user   = User::where('id',$record['user_id'])->find();
        if (!$user) {
            halt('user');
            throw new MessageException('驳回失败，找不到该用户');
        }
        $openidWhere['user_id'] = $record['user_id'];
        $openid = $UserOauth->getOpenId($openidWhere);
        // 启动事务
        Db::startTrans();
        try {
            // halt('我进来了');
            $record->status = 3;
            $record->back_mark = $params['back_mark'];
            $record->save();
            
            if ($openid) {
                $sedData = [
                    'touser'        => $openid,
                    'back_mark'     => $params['back_mark'],
                    'real_name'     => $user['real_name'],
                    'status'        => '驳回',
                    'time'          => date("Y年m月d日"),
                    'admin'         => $admin['nickname'],
                    'user_id'       => $user['id'],
                ];
                $wechat->sendDownMessage($sedData);
            }
            // 提交事务
            Db::commit();
            return $record;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }

    }
    /**
     * @Description: 添加申请入住记录
     * @author: xiayu <cb1071403016@126.com>
     * @param [type] $params
     * @Date: 2022-10-26 11:16:34
     * @version: 1.0.0
     * @return [type]
     */
    public static function addRecord($params){

        // $data = [
        //     'user_id' => $params['id']
        // ];
        return RoomLeaseRecord::create($params);
    }
    /**
     * @Description: 分配房间
     * @author: xiayu <cb1071403016@126.com>
     * @Date: 2022-10-26 11:16:59
     * @version: 1.0.0
     * @return [type]
     */
    public function allot($params){
        // print_r($params);
        $wechat     = new WechatH5Service;
        $UserOauth  = new UserOauthLogic;

        // halt(empty($params['type']));

        $roomWhere['id'] = $params['room_id'];
        

        //获取房间详情
        $RoomRes = Room::getRoom($roomWhere);
        // 判断用户是否已入住
        $userWhere['user_id'] = $params['user_id'];
        $userWhere['status']  = 1;

        $userId = RoomLeaseRecord::getUserRecord($userWhere);

        if($userId && empty($params['type'])){
            throw new MessageException('分配失败，该用户已分配');
        }


        if(!isset($RoomRes['roomType']['live_number'])){
            throw new MessageException('分配失败，找不到该房型');
        }

        if($RoomRes['roomType']['live_number'] <= $RoomRes['use_people'] ){
            throw new MessageException('分配失败，该房间已住满');
        }
        Db::startTrans();
        try {

        // 添加房间入住人数
        $saveValue = Room::saveValue($roomWhere, 'use_people', 1,$params['user_id']);

        if (!empty($params['before_room_id'])) {
            $beforeRoomWhere['id'] = $params['before_room_id'];
            $Reduction = Room::saveValue($beforeRoomWhere, 'use_people', -1,$params['user_id']);
        }

        $recordWhere['id'] = $params['id'];

        if(empty($params['type'])){
            // 分配
            $recordData = [
                'room_id'       => $params['room_id'],
                'start_time'    => strtotime($params['start_time']),
                'lease_mark'    => $params['lease_mark'],
                'status'        => 1
            ];
        }else{
            // 换宿
            $recordData = [
                'room_id'           => $params['room_id'],
                'change_time'       => time(),
                'status'            => 1
            ];
            $returnRecordData = [
                'user_id'       => $params['user_id'],
                'before_room_id'=> $params['before_room_id'],
                'after_room_id' => $params['room_id'],
                'status'        => 1
            ];
            ReturnRecord::create($returnRecordData);
        }
        
        $saveRecord = RoomLeaseRecord::updateRecord($recordWhere, $recordData);
        
        $openidWhere['user_id'] = $params['user_id'];
        $openid = $UserOauth->getOpenId($openidWhere);
        $infoWhere['id'] = $params['user_id'];
        $userInfo = User::where($infoWhere)->find();
        if($openid){
            $sedData = [
                'touser'        => $openid,
                'real_name'     => $userInfo['real_name'],
                'room_name'     => $RoomRes['building']['name'] . $RoomRes['building']['building_number'] . $RoomRes['name'],
                'time'          => date("Y年m月d日"),
                'user_id'       => $params['user_id']
            ];
            $wechat->sendAuditMessage($sedData);
        }
            Db::commit();
            return $saveRecord;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        
    }
    /**
     * @Description: 获取用户申请记录
     * @author: xiayu <cb1071403016@126.com>
     * @param [type] $where      //查询条件
     * @Date: 2022-11-09 10:29:26
     * @version: 1.0.0
     * @return [type]
     */
    public static function getRecord($where){

        $res = RoomLeaseRecord::getRecord($where);

        return $res;
    }


    /**
     * @Description: 移除租户
     * @author: xiayu <cb1071403016@126.com>
     * @Date: 2022-11-23 15:58:58
     * @version: 1.0.0
     * @return [type]
     */    
    public function removeUser($params){
        $wechat     = new WechatH5Service;
        $UserOauth  = new UserOauthLogic;
        // $where['room_id']   = $params['room_id'];
        // $where['user_id']   = $params['id'];
        $where['status']    = 1;
        $where['id'] = $params['id'];
        $record = RoomLeaseRecord::where($where)->find();

       

        if(!$record){
            throw new MessageException('退宿失败，找不到入住记录');
        }

        $PayRecordWhere['user_id'] = $record['user_id'];
        $PayRecordWhere['status']  = 0; //待支付字段
        $payRecord = PayRecord::withoutGlobalScope(['pid'])->where($PayRecordWhere)->find();
        
        if($payRecord){
            throw new MessageException('退宿失败，该用户还有待缴房租未处理');
        }

        Db::startTrans();
        try {
            // 提交事务
         
        $recordWhere['id'] = $record['id'];
        $recordData = [
            // 'room_id'       => $params['room_id'],
            'end_time'    => time(),
            'status'      => 2,
            'keep_file'   => $params['url']
        ];
        $saveRecord = RoomLeaseRecord::updateRecord($recordWhere, $recordData);

        $roomWhere['id'] = $record['room_id'];
        $saveValue = Room::saveValue($roomWhere, 'use_people', -1,$record['user_id']);

        $user = User::find($record['user_id']);
        $openidWhere['user_id'] = $record['user_id'];
        $openid = $UserOauth->getOpenId($openidWhere);
        // halt($user['id']);
        if ($openid) {
            
            $sedData = [
                'touser'        => $openid,
                'real_name'     => $user['real_name'],
                'status'        => '已通过',
                'time'          => date("Y年m月d日"),
                'user_id'       => $record['user_id']
            ];
            // halt($sedData);
            $wechat->sendOutMessage($sedData);
        }
            Db::commit();
            return $saveRecord;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
    }
}
